﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JuCheap.Core.Interfaces;
using JuCheap.Core.Models.Filters;
using JuCheap.Core.Models.ViewModels;
using Microsoft.AspNetCore.Mvc;

namespace JuCheap.Core.Web.Controllers
{
    public class StatisticsController : Controller
    {
        private IReportFormService _iReportFormService;

        private IRepository _iRepository;
        public StatisticsController(IReportFormService iRepository, IRepository workerRepository)
        {
            _iReportFormService = iRepository;
            _iRepository = workerRepository;
        }
        public string GetStatus(int status)
        {
            if (status == 1)
                return "启用";
            return "停用";
        }
        public IActionResult Index()
        {
            ReportFormViewModel reportFormViewModel = new ReportFormViewModel();
            return View();
        }

        public async Task<IActionResult> GetListWithPager(OriganizationReportFilter filter)
        {
            if (string.IsNullOrEmpty(filter.orginationName) ||
                filter.orginationName == "请选择")
                filter.orginationName = "";
            filter.rows = 1000;

            var result = await _iReportFormService.GetReport(filter);
            List<string> jobs = new List<string>();
            foreach (var r in result.rows)
            {
                foreach (var j in r.Employers)
                {
                    if (!jobs.Contains(j.Key))
                    {
                        jobs.Add(j.Key);
                    }
                }
            }
            //if(filter.status) 

            foreach (var r in result.rows)
            {
                Dictionary<string, int> Employers = new Dictionary<string, int>();
                foreach (var j in jobs)
                {
                    if (!r.Employers.Keys.Contains(j))
                    {
                        Employers.Add(j, 0);
                    }
                    else
                    {
                        Employers.Add(j, r.Employers.Where(w=>w.Key == j).First().Value);
                    }
                }

                r.Employers = Employers;

                r.State = GetStatus(r.Status);
                //r.Employers
            }

            
            return Json(result);
        }

        public async Task<IActionResult> GetStatistics(OriganizationReportFilter filter)
        {
            if (string.IsNullOrEmpty(filter.orginationName) ||
                filter.orginationName == "请选择")
                filter.orginationName = "";
            filter.rows = 1000;

            var result = await _iReportFormService.GetReport(filter);
            //var jobs = await _iRepository.GetJobPositions(new JobPositionFilter() { rows=10000, });
            List<string> jobs = new List<string>();
            foreach (var r in result.rows)
            {
                foreach (var j in r.Employers)
                {
                    if (!jobs.Contains(j.Key))
                    {
                        jobs.Add(j.Key);
                    }
                }
                r.State = GetStatus(r.Status);
                //r.Employers
            }

            foreach (var r in result.rows)
            {
                Dictionary<string, int> Employers = new Dictionary<string, int>();
                foreach (var j in jobs)
                {
                    if (!r.Employers.Keys.Contains(j))
                    {
                        Employers.Add(j, 0);
                    }
                    else
                    {
                        Employers.Add(j, r.Employers.Where(w => w.Key == j).First().Value);
                    }
                }

                r.Employers = Employers;

                r.State = GetStatus(r.Status);
            }
            return Json(result);
        }

        public async Task<IActionResult> GetGroupWorker(OriganizationReportFilter filter)
        {
            if (string.IsNullOrEmpty(filter.orginationName) ||
                filter.orginationName == "请选择")
                filter.orginationName = "";
            filter.page = 0;
            filter.rows = 1000;
            var result = await _iReportFormService.GetReport(filter);
            //if(filter.status) 
            foreach (var r in result.rows)
            {
                r.WorkerCount = r.Employers.Sum(e => e.Value);
                r.State = GetStatus(r.Status);
                //r.Employers
            }
            return Json(result);
        }




        public async Task<IActionResult> GetWorkerAttend(WorkerAttendFilter filter)
        {
            var workerFilter = new WorkerFilter
            {
                name = filter.Name,
                CompanyId = filter.CompanyId,
                JobPositionTypeId = filter.JobPositionTypeId,
                page = filter.page,
                rows = 10000,
                keywords = ""
            };
            List<WorkAttendance> result = new List<WorkAttendance>();
            var workerList = await _iRepository.GetWorkers(workerFilter);
            List<string> li = new List<string>();
            foreach(var worker in workerList.rows)
            {
                result.Add(new WorkAttendance() {
                     WorkerName = worker.Name,
                     JobName = worker.JobPositionName,
                });
                li.Add(worker.Name);
            }
            filter.WorkName = li;

            var year = filter.Year;
            var month = filter.Month;
            filter.Date = new DateTime(year, month, 1).ToShortDateString();
            var attendance = _iReportFormService.GetWorkerAttend(filter);
            foreach(var worker in result)
            {
                var w = attendance.Where(a => a.Worker.Name == worker.WorkerName).ToList();

                for (DateTime dt = new DateTime(year, month, 1); dt < new DateTime(year, month + 1, 1); dt = dt.AddDays(1))
                {
                    var d = w.Where(a => a.Date == dt).FirstOrDefault();
                    if (d == null)
                    {
                        worker.workerDates.Add(new WorkerDate()
                        {
                            Date = dt.Date.ToString("yyyy-MM-dd"),
                            FirstTime = "",
                            LastTime = "",
                        });
                    }
                    else
                    {
                        worker.workerDates.Add(new WorkerDate()
                        {
                            Date = d.Date.ToString("yyyy-MM-dd"),
                            FirstTime = d.FirstTime ==null ? "" :d.FirstTime.Value.Hour.ToString(),
                            LastTime = d.LastTime == null ? "" : d.LastTime.Value.Hour.ToString(),
                        });
                    }
                }

            }

            //CheckWorkAttendanceViewModel


            return Json(result);
        }


        public async Task<IActionResult> GetWorkerStatistic(WorkerAttendFilter filter)
        {
            var workerFilter = new WorkerFilter
            {
                name = filter.Name,
                CompanyId = filter.CompanyId,
                JobPositionTypeId = filter.JobPositionTypeId,
                page = filter.page,
                rows = 10000,
                keywords = ""
            };
            List<WorkerStatistic> result = new List<WorkerStatistic>();
            var workerList = await _iRepository.GetWorkers(workerFilter);
            List<string> li = new List<string>();
            foreach (var worker in workerList.rows)
            {
                result.Add(new WorkerStatistic()
                {
                    WorkerName = worker.Name,
                    JobName = worker.JobPositionName,
                });
                li.Add(worker.Name);
            }
            filter.WorkName = li;

            var year = filter.Year;
            var month = filter.Month;
            filter.Date = new DateTime(year, month, 1).ToShortDateString();
            var attendance = _iReportFormService.GetWorkerAttend(filter);
            foreach (var worker in result)
            {
                var attend = attendance.Where(a => a.Worker.Name == worker.WorkerName).ToList();
                worker.AddedHour = attend.Sum(a => a.AddedHour);
                worker.TotalHour = attend.Sum(a => a.TotalHour);
                worker.AllHour = worker.AddedHour + worker.TotalHour;
                //var w = attendance.Where(a => a.Worker.Name == worker.WorkerName).ToList();

                //for (DateTime dt = new DateTime(year, month, 1); dt < new DateTime(year, month + 1, 1); dt = dt.AddDays(1))
                //{
                //    var d = w.Where(a => a.Date == dt).FirstOrDefault();
                //    if (d == null)
                //    {
                //        worker.AddedHour = 0;
                //        worker.TotalHour = 0;
                //        worker.AllHour = 0;
                //    }
                //    else
                //    {
                //        worker.AddedHour = d.AddedHour;
                //        worker.TotalHour = d.TotalHour;
                //        worker.AllHour = d.AddedHour + d.TotalHour;
                //    }
                //}

            }

            //CheckWorkAttendanceViewModel


            return Json(result);
        }


        public IActionResult ManagerStatis()
        {
            return View();
        }

        public IActionResult GroupWorkerStatis()
        {
            return View();
        }

        public IActionResult WorkerStatis()
        {
            return View();
        }

        public IActionResult AttendanceStatis()
        {
            return View();
        }

        public IActionResult WorkerDateStatis()
        {
            return View();
        }
    }


    public class WorkAttendance
    {
        public string WorkerName { get; set; }

        public string JobName { get; set; }

        public List<WorkerDate> workerDates = new List<WorkerDate>();
    }

    public class WorkerDate
    {
        public string Date { get; set; }
        public string FirstTime { get; set; }
        public string LastTime { get; set; }
    }

    public class WorkerStatistic
    {
        public string WorkerName { get; set; }

        public string JobName { get; set; }

        public double TotalHour { get; set; }
        public double AddedHour { get; set; }

        public double AllHour { get; set; }
    }
}